package com.ascentive.finallyfast.deepclean;

import java.util.ArrayList;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ascentive.finallyfast.R;

public class DeepCleanListAdapter extends ArrayAdapter<DeepCleanListItem>{

	private final Activity mContext;
	private ArrayList<DeepCleanListItem> mItems = null;
	private DeepCleanListAdapterListener mListener;


	ViewHolder holder;
	
	public DeepCleanListAdapter(Activity context, ArrayList<DeepCleanListItem> items) {
		super(context, R.layout.deep_clean_list, items);
		mContext = context;
		mItems = items;
 	}

	// static to save the reference to the outer class and to avoid access to
	// any members of the containing class
	static class ViewHolder {
		public ImageView imageView;
		public TextView textView;
		public CheckBox checkBox;
	}
	
	int count=0;
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// ViewHolder will buffer the assess to the individual fields of the row
		// layout
		final int pos = position;
		
		// Recycle existing view if passed as parameter
		// This will save memory and time on Android
		// This only works if the base layout for all classes are the same
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = mContext.getLayoutInflater();
			rowView = inflater.inflate(R.layout.deep_clean_list_row, null, true);
			holder = new ViewHolder();
			holder.textView = (TextView) rowView.findViewById(R.id.txt);
			holder.imageView = (ImageView) rowView.findViewById(R.id.image);
			holder.checkBox = (CheckBox) rowView.findViewById(R.id.chk);
			rowView.setTag(holder);
		} else {
			holder = (ViewHolder) rowView.getTag();
		}

		holder.textView.setText(mItems.get(position).getItemName());
		holder.imageView.setImageResource(mItems.get(position).getImage());
		holder.checkBox.setChecked(mItems.get(position).isCheckBoxValue());
		
		holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					// @Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						mItems.get(pos).setCheckBoxValue(isChecked);
						if(isChecked)
							Log.v(null, "checked "+mItems.get(pos).getItemName());
						else
							Log.v(null, "un checked "+mItems.get(pos).getItemName());
							
						mListener.onItemChecked(mItems.get(pos));
					}
		});

 		return rowView;
	}
	
	public ViewHolder getViewHolder()
	{
		return holder;
	}

	public void setListener(DeepCleanListAdapterListener listener){
		mListener = listener;
	}
}
